package com.CookieSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.sql.rowset.serial.SerialException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpCookie;
import java.util.Date;

public class CookieTest extends HttpServlet{

  public  void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException,IOException{

      request.setCharacterEncoding("UTF-8");
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();

      Cookie[] cookies = request.getCookies();

      if(cookies !=null){

          out.write("您上次访问的时间是：");
          for(int i =0;i<cookies.length;i++){

              Cookie cookie = cookies[i];
              if(cookie.getName().equals("lastAccessTime")){
                  Long lastAccessTime = Long.parseLong(cookie.getValue());
                  Date date = new Date(lastAccessTime);
                  out.write(date.toLocaleString());
              }
          }
      }else{

            out.write("这是您第一次访问本站！");
      }
      Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
      response.addCookie(cookie);

  }

  public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

      doGet(request,response);
  }

    public static void main(String[] args) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
         HttpSession session = request.getSession();
         session.setAttribute("name","zhangsan");
        System.out.println(session.getAttribute("name"));
    }
























}
